package com.woniuxy.pxxt.controller;

import com.qiniu.storage.model.DefaultPutRet;
import com.woniuxy.pxxt.common.result.Result;
import com.woniuxy.pxxt.utils.DateUtil;
import com.woniuxy.pxxt.utils.QiniuUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.util.*;

/**
 * 七牛云工具类
 * @Author: QinYD
 * @Date: 2022/3/8 09:27
 * @Description:
 */
@Slf4j
@RestController
@RequestMapping("/qiniu")
public class QiNiuController {

    @Autowired
    private QiniuUtil qiniuUtil;

    /**
     * 七牛云文件上传
     *
     * @param file 文件
     * @return
     */
    @ApiOperation(value = "七牛云文件上传")
    @PostMapping("/upload")
    @ResponseBody
    public Result upload(MultipartFile[] file) {
        ResponseEntity responseEntity;
        if (file.length <= 0) {
            return Result.fail().message("上传文件不能为空");
        }
        if (file[0].isEmpty()) {
            return Result.fail().message("上传文件不能为空");
        }
        try {
            BufferedInputStream fileInputStream = new BufferedInputStream(file[0].getInputStream());
            String originalFilename = file[0].getOriginalFilename();
            String fileExtend = originalFilename.substring(originalFilename.lastIndexOf("."));
            String yyyyMMddHHmmss = DateUtil.format(new Date(), "yyyyMMddHHmmss");
            //默认不指定key的情况下，以文件内容的hash值作为文件名
            String fileKey = UUID.randomUUID().toString().replace("-", "") + "-" + yyyyMMddHHmmss + fileExtend;
            Map<String, Object> map = new HashMap<>();
            DefaultPutRet uploadInfo = qiniuUtil.upload(fileInputStream, fileKey);
            map.put("fileName", uploadInfo.key);
            map.put("originName", originalFilename);
            map.put("size", file[0].getSize());
            //七牛云文件私有下载地址（看自己七牛云公开还是私有配置）
//            map.put("url", "/linfen/qiniu/private/file/" + uploadInfo.key);
            //七牛云公开下载地址
//            map.put("url", "/api/qiniu/file/" + uploadInfo.key);
//            log.info("文件：" + JSON.toJSONString(map));
            map.put("url", qiniuUtil.getFileDomain()+"/"+uploadInfo.key);
            System.out.println(map);
            return Result.ok(map).message("上传文件成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail().message("上传文件失败");
        }
    }



    /**
     * 七牛云文件上传 多文件
     *
     * @param file 文件
     * @return
     */
    @ApiOperation(value = "七牛云文件上传")
    @PostMapping("/uploads")
    @ResponseBody
    public Result uploads(MultipartFile[] file) {
        ResponseEntity responseEntity;
        if (file.length <= 0) {
            return Result.fail().message("上传文件不能为空");
        }
        if (file[0].isEmpty()) {
            return Result.fail().message("上传文件不能为空");
        }
        try {
            List<Map> list =  new ArrayList<>();
            for(int i = 0; i< file.length ; i++){
                BufferedInputStream fileInputStream = new BufferedInputStream(file[0].getInputStream());
                String originalFilename = file[i].getOriginalFilename();
                String fileExtend = originalFilename.substring(originalFilename.lastIndexOf("."));
                String yyyyMMddHHmmss = DateUtil.format(new Date(), "yyyyMMddHHmmss");
                //默认不指定key的情况下，以文件内容的hash值作为文件名
                String fileKey = UUID.randomUUID().toString().replace("-", "") + "-" + yyyyMMddHHmmss + fileExtend;
                Map<String, Object> map = new HashMap<>();
                DefaultPutRet uploadInfo = qiniuUtil.upload(fileInputStream, fileKey);
                map.put("fileName", uploadInfo.key);
                map.put("originName", originalFilename);
                map.put("size", file[i].getSize());
                //七牛云文件私有下载地址（看自己七牛云公开还是私有配置）
//            map.put("url", "/linfen/qiniu/private/file/" + uploadInfo.key);
                //七牛云公开下载地址
//            map.put("url", "/api/qiniu/file/" + uploadInfo.key);
//            log.info("文件：" + JSON.toJSONString(map));
                map.put("url", qiniuUtil.getFileDomain()+"/"+uploadInfo.key);
                list.add(map);
                System.out.println(map);
            }
            return Result.ok(list).message("上传文件成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail().message("上传文件失败");
        }
    }




    /**
     * 七牛云私有文件下载
     *
     * @param filename 文件名
     * @return
     */
    @ApiOperation(value = "七牛云私有文件下载")
    @GetMapping("/private/file/{filename}")
    public void privateDownload(@PathVariable("filename") String filename, HttpServletResponse response) {
        if (filename.isEmpty()) {
            return;
        }

        try {
            System.out.println("进方法了-------------------------------------------------");
            String privateFile = qiniuUtil.getPrivateFile(filename);
            log.info("文件下载地址：" + privateFile);
            response.sendRedirect(privateFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 七牛云文件下载
     *
     * @param filename 文件名
     * @return
     */
    @ApiOperation(value = "下载七牛云文件")
    @GetMapping("/file/{filename}")
    public void download(@PathVariable("filename") String filename, HttpServletResponse response) {
        if (filename.isEmpty()) {
            return;
        }

        try {
            String privateFile = qiniuUtil.getFile(filename);
            log.info("文件下载地址：" + privateFile);
            response.sendRedirect(privateFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 七牛云删除文件
     *
     * @param filename 文件名
     * @return
     */

    @ApiOperation(value = "删除七牛云文件")
    @DeleteMapping("/delete/file/{filename}")
    public Result deleteFile(@PathVariable("filename") String filename, HttpServletResponse response) {
        if (filename.equals("null") || filename.isEmpty()) {
            return Result.fail().message("未知文件");
        }
        System.out.println(filename);
        try {
            boolean result = qiniuUtil.delete(filename);
            if (result) {
                return Result.ok().message("文件删除成功");
            }else {
                return Result.fail().message("文件删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail().message("文件删除失败");
        }
    }
}